package com.green.cosme.servlet;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.green.cosme.batch.scraper.Item;
import com.green.cosme.util.PMF;

/**
 * ReadCosmetics ServletClass
 * 
 * @author M.T
 * 
 */
@SuppressWarnings("serial")
// #@@range_begin(servlet_body)
public class CreateJsonServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		// select data from BigTable
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Item.class);
		query.setOrdering("categoryCode");
		query.setOrdering("seibunCode");
		query.setOrdering("price desc");

		// setting data to velocity context
		List<Item> items = (List<Item>) query.execute();

		// transform to JSON format
		Gson gson = new Gson();
		String jsonstring = gson.toJson(items);

		// reflect data to OutputStream
		resp.setContentType("application/json; charset=UTF-8");
		resp.getWriter().println(jsonstring);

	}
}
// #@@range_end(servlet_body)
